﻿using IdentityModel;
using Microsoft.Extensions.Logging;
using OA.Infrastructure.Authentication.Abstractions;
using System.Security.Claims;

namespace OA.Infrastructure.Authentication.Jwt;

public class JwtUserPool : UserPoolBase
{
    private readonly DbContext _context;
    private readonly ILogger<JwtUserPool> _logger;

    public JwtUserPool(DbContext context, ILogger<JwtUserPool> logger)
    {
        _context = context;
        _logger = logger;
    }

    public override async Task<ICollection<Claim>?> ValidateAsync(string account, string password)
    {
        var user = await _context.Set<User>().Select(n => new { n.Id, n.Account, n.Password }).FirstOrDefaultAsync(n => n.Account == account);

        if (user is not null &&
            (App.Validate(user.Password, password) ||
            user.Password.Equals(System.Web.HttpUtility.UrlDecode(password)) ||
            user.Password == password))
        {
            var claims = new Claim[]
            {
                new Claim(JwtClaimTypes.Subject, user.Id.ToString()),
                new Claim(JwtClaimTypes.Name, user.Account),
                new Claim(JwtClaimTypes.JwtId, Guid.NewGuid().ToString("N")),
                new Claim(JwtClaimTypes.IdentityProvider, "local"),
                new Claim(JwtClaimTypes.AuthenticationMethod, "pwd")
            };

            _logger.LogInformation("用户：{account}认证成功", user.Account);

            return claims;
        }

        return null;
    }
}